<?php
/**
 * @copyright Copyright (c) 2020 Robin Appelman <robin@icewind.nl>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OCA\DocumentServer\OnlyOffice;

use OCA\Onlyoffice\AppConfig;
use OCP\IURLGenerator;

class AutoConfig {
	private $urlGenerator;
	private $appConfig;

	public function __construct(IURLGenerator $urlGenerator, AppConfig $appConfig) {
		$this->urlGenerator = $urlGenerator;
		$this->appConfig = $appConfig;
	}

	public function autoConfigIfNeeded() {
		if ($this->shouldAutoConfig()) {
			$this->autoConfig();
		}
	}

	/**
	 * Check if onlyoffice is not configured and we should fill our defaults
	 *
	 * @return bool
	 */
	private function shouldAutoConfig(): bool {
		return $this->appConfig->GetDocumentServerUrl() === '';
	}

	/**
	 * Fill the documentserver url and other defaults
	 */
	private function autoConfig() {
		$url = substr($this->urlGenerator->linkToRouteAbsolute('documentserver_community.Static.webApps',
			['path' => '_']), 0, -strlen('/web-apps/_'));
		$this->appConfig->SetDocumentServerUrl($url);

		$formatSettings = $this->appConfig->FormatsSetting();
		$defaultFormats = array_map(function ($settings) {
			return $settings["def"] ?? false;
		}, $formatSettings);
		$editFormats = array_map(function ($settings) {
			return $settings["edit"] ?? false;
		}, $formatSettings);

		$defaultFormats = array_merge(
			array_filter($defaultFormats, function ($settings) {
				return $settings;
			}),
			["odp" => true, "ods" => true, "odt" => true, "pptx" => true, "xlsx" => true, "docx" => true, "doc" => true, "ppt" => true, "xls" => true]
		);
		$editFormats = array_merge(
			array_filter($editFormats, function ($settings) {
				return $settings;
			}),
			["csv" => true, "odp" => true, "ods" => true, "odt" => true, "rtf" => true, "txt" => true]
		);

		$this->appConfig->SetDefaultFormats($defaultFormats);
		$this->appConfig->SetEditableFormats($editFormats);
		$this->appConfig->SetSameTab(true);
	}
}
